<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="退货单号:">
        <el-input v-model="queryParams.custReturnOrderItemNo" size="small" placeholder="请输入退货单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="子订单号:">
        <el-input v-model="queryParams.custSalesOrderItemNo" size="small" placeholder="请输入订单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="申请时间自:">
        <el-date-picker v-model="queryParams.createTimeBegin" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" size="small" placeholder="选择申请时间" clearable />
      </el-form-item>
      <el-form-item label="申请时间至:">
        <el-date-picker v-model="queryParams.createTimeEnd" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" size="small" placeholder="选择申请时间" clearable />
      </el-form-item>
      <el-form-item label="退货单状态:">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" >
           <el-option v-for="status in options.statuss" :key="status.key" :label="status.label" :value="status.key"  />
         </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">

     <!-- <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="batchProcess">处理退单</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button v-hasPermission="['order:salesOrder:insert']" type="info" icon="el-icon-upload2" size="mini" @click="openUploadDialog">批量退单导入</el-button>
      </el-col>
      <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />

     <!-- <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" /> -->
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="page.records" highlight-current-row @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退货单号" align="center" prop="returnOrderId" sortable width="155"/>
      <el-table-column label="子订单号" align="center" show-overflow-tooltip sortable width="180">
       <template slot-scope="scope">
        <el-button type="text" @click="handleOrderView(scope.row)">{{ scope.row.custSalesOrderItemNo }}</el-button>
      </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="90">
       <template slot-scope="scope">
          <span>{{ scope.row.status | returnStatusFilter }}</span>
        </template>
      </el-table-column>
       <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户SKU" align="center" prop="custSkuId" sortable width="155"/>
      <el-table-column label="客户SPU" align="center" prop="custSpuId" sortable width="155"/>
      <el-table-column label="退款金额" align="center"  prop="money" />
      <el-table-column label="里程额" align="center" prop="mileagePrice" />
      <el-table-column label="现金额" align="center" prop="paymentPrice" />
      <el-table-column label="退款数量" align="center" prop="qty" />
      <el-table-column label="报错原因" align="center" prop="importErrorMesg" width="255"/>
      <el-table-column label="退单时间" align="center" prop="lastUpdDt" width="180"/>
       
     <!-- <el-table-column label="处理时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['order:returnOrder:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['order:returnOrder:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

   <el-dialog :title="uploadDialog.title" :visible.sync="uploadDialog.visible" width="400px" append-to-body>
     <div v-loading="uploadLoading">
       <el-upload
         ref="upload"
         :limit="1"
         :headers="uploadData.headers"
         :action="uploadData.url + '?updateSupport=' + uploadData.updateSupport"
         :data="uploadData.params"
         :disabled="uploadData.isUploading"
         :on-progress="handleFileUploadProgress"
         :on-success="handleFileSuccess"
         :on-error="handleFileError"
         :auto-upload="false"
         accept=".xlsx, .xls"
         drag
       >
         <i class="el-icon-upload" />
         <div class="el-upload__text">
           将文件拖到此处，或
           <em>点击上传</em>
         </div>
         <div slot="tip" class="el-upload__tip">
           <el-select v-model="uploadData.params.customerNo" style="width: 100%" filterable clearable placeholder="请选择下单客户">
             <el-option v-for="option in options.customers" :key="option.id" :label="option.customerName" :value="option.id" />
           </el-select>

           <el-link type="info" style="font-size:12px" @click="handleDownloadTemplate">下载模板</el-link>
         </div>
         <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
       </el-upload>
       <div slot="footer" class="dialog-footer">
         <el-button type="primary" @click="confirmUploadDialog">确 定</el-button>
         <el-button @click="resetUploadDialog">取 消</el-button>
       </div>
     </div>
    </el-dialog>
    <!-- 分页 -->
    </div>
</template>

<script>
import ReturnOrderItemApi from '@/api/order/ReturnOrderItemApi'
import AccountingApApi from '@/api/accounting/AccountingApApi'
import CustomerApi from '@/api/basic/CustomerApi'
import appConstant from '@/constant/AppConstant'
import AuthUtils from '@/utils/AuthUtils'
export default {
  name: 'OmsReturnOrderList',
  filters: {
    returnStatusFilter(item) {
      const values = appConstant.returnStatusList.filter(value => value.key === item)
      if (values && values.length > 0) {
        return values[0].label
      } else {
        return ''
      }
    }
   },
  data() {
    return {
      options: {
        sysYnTypeOptions: [],
        statuss: appConstant.returnStatusList,
        customers: []
      },
      queryParams: {
        custSalesOrderItemNo: null,
        custReturnOrderItemNo: null,
        salesOrderNo: null,
        createTimeBegin: null,
        createTimeEnd: null,
        createTime: null,
        status: null,
        isValid: this.$constant.Y,
        sortProperty: null,
        sortDirection: null
      },
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      uploadDialog: {
        title: '退单批量导入',
        visible: false
      },
      uploadData: {
        headers: { Authorization: 'Bearer ' + AuthUtils.getToken() }, // 上传请求头
        url: process.env.VUE_APP_BASE_API + '/order/returnOrderItem/importData', // 上传的地址
        params: {
          customerNo: '1353968310689075200' // 会员商城
        },
        isUploading: false, // 是否禁用上传
        updateSupport: 0 // 是否更新已经存在的数据
      },
      loading: true,
      uploadLoading: false,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      CustomerApi.list().then(response => {
        this.options.customers = response.data
      })
    },
    handleAdd() {
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return ReturnOrderItemApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
    },
    batchProcess() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        return false
      }
      for (let i=0; i<this.multipleSelection.length; i++) {
        const row = this.multipleSelection[i]
        // 有结算成功或结算失败的订单时，不允许提交
        if (row.status === 'PROCESSED'||row.status === 'SETTLED') {
          this.$message.error('处理后或已下账汇总的退单不能提交!')
          return false
        }
      }
      const ids = this.multipleSelection.map(item => item.id)
       AccountingApApi.batchProcessReturn(ids).then(() => {
         this.$message.success('处理退单成功!')
         this.handleQuery()
       })
    },
    handleQuery() {
      this.loading = true
      ReturnOrderItemApi.page(this.queryParams, this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    handleOrderView(row) {
      this.$router.push({ path: `/accountingAp/accountingApReturnList/${row.custSalesOrderItemNo}` })
    },
    handleExport() {
      this.$confirm('是否确认导出所有退货单数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return ReturnOrderApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    handleSortChange(sort) {
      if (sort.order) {
        this.queryParams.sortProperty = sort.prop
        this.queryParams.sortDirection = sort.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.queryParams.sortProperty = null
        this.queryParams.sortDirection = null
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    openUploadDialog() {
      this.resetUploadDialog()
      this.uploadDialog.visible = true
    },
    confirmUploadDialog() {
      if (this.uploadData.params.customerNo) {
        this.uploadLoading = true
        this.$refs.upload.submit()
      } else {
        this.$message.warning('请先选择客户')
      }
    },
    resetUploadDialog() {
      this.uploadDialog.visible = false
      this.uploadData.params.customerNo = '1353968310689075200' // 会员商城
    },
    handleDownloadTemplate() {
      ReturnOrderItemApi.importTemplate().then(response => {
        this.$common.download(response.data)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.uploadData.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadLoading = false
      this.uploadDialog.visible = false
      this.uploadData.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.data ? response.data : response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.queryParams.status = null
      this.handleQuery()
    },
    // 文件上传失败处理
    handleFileError(response, file, fileList) {
      this.uploadLoading = false
    },
    resetQuery() {
      this.page.current = 1
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
